package com.njlime.cms.controller.sys;

import com.njlime.cms.entities.Channel;
import com.njlime.cms.repository.sys.ChannelDao;
import com.njlime.cms.service.sys.ChannelService;
import com.njlime.cms.util.QRUtils;
import com.njlime.core.base.controller.BaseController;
import com.njlime.core.exception.ExceptionState;
import com.njlime.member.entiies.TMemberGroup;
import com.njlime.sys.security.util.UserUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 频道管理
 * Created by Dean on 2017/8/10.
 */
@Controller
@RequestMapping(value = "/cms/channel")
public class ChannelController extends BaseController {

    @Resource
    private ChannelService channelService;

    @Resource
    private ChannelDao channelDao;
    /**
     * 跳转热点管理页面
     *
     * @return
     */
    @RequestMapping(value = "toChannel")
    public ModelAndView roleManage(HttpServletRequest request) {

        ModelAndView modelAndView = new ModelAndView("/sys/content/channel/index");
        TMemberGroup info = new TMemberGroup();
        int unitId = UserUtils.getUser().getRootUnit().getId();
        info.setUnit_id(unitId);
        modelAndView.addObject("unitId", unitId);
        Map<String, Object> map = channelService.getChannelByShort(unitId, 1);
        Date date = new Date();
        Channel channel = new Channel();
        channel.setCreate_time(date);
        channel.setChannel_type(Channel.CHANNEL_TYPE_0);
        channel.setChannel_short(1);
        channel.setUnit_id(unitId);
        if (map == null) {
            channelDao.save(channel);

        }else{
            channel.setId(Integer.parseInt(map.get("id").toString()));
        }
        modelAndView.addObject("channelShort", channel.getId());
        return modelAndView;
    }

    /**
     * 获取详情
     *
     * @param channelShort
     * @return
     */
    @RequestMapping(value = "info", method = RequestMethod.GET)
    @ResponseBody
    public String info(Integer channelShort, Integer unitId) {
        logger.info("/cms/channel/info");
        try {
            unitId = UserUtils.getUser().getRootUnit().getId();
            if (channelShort != null && channelShort.intValue() >= 0) {

            } else {
                return toJsonSuccessData(new Object());
            }
            return toJsonSuccessData(channelService.getChannelByShort(unitId, channelShort));
        } catch (Exception e) {
            logger.error("", e);
        }
        return "";
    }


    @RequestMapping(value = "add", produces = "application/json; charset=utf-8")
    @ResponseBody
    public String saveChannel(Channel info, String columns, HttpServletRequest request, HttpServletResponse response) {
        logger.info("/cms/channel/saveChannel");
        Map<String, Object> jsonList = new HashMap<String, Object>();

        try {

            int unitId = UserUtils.getUser().getRootUnit().getId();

            info.setCreator(UserUtils.getUser().getId());
            info.setUnit_id(unitId);
            info.setUpdater(UserUtils.getUser().getId());
            Map<String, Object> map = channelService.getChannelByShort(info.getUnit_id(), info.getChannel_short());
            Date date = new Date();
            info.setCreate_time(date);
            if (map == null) {
                channelService.save(info, columns);
            } else {
                channelService.update(info, columns);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return toJsonSuccessData(info);
    }

    @RequestMapping(value = "setting", produces = "application/json; charset=utf-8")
    @ResponseBody
    public String settingChannel(Channel info, HttpServletRequest request, HttpServletResponse response) {
        try{
            int unitId = UserUtils.getUser().getRootUnit().getId();
            info.setUnit_id(unitId);
            channelService.setting(info);
            return toJsonSuccessData();
        }catch (Exception e){
            return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "设置失败");
        }
    }

    /**
     * 新注册单位创建所有频道
     *
     * @param info
     * @param unitId   新单位id
     * @param request
     * @param response
     * @return
     */
    /*@RequestMapping(value = "addAll", produces = "application/json; charset=utf-8")
    @ResponseBody
    public String saveChannelAll(Channel info, int unitId, HttpServletRequest request, HttpServletResponse response) {
        logger.info("/cms/channel/saveChannel");
        Map<String, Object> jsonList = new HashMap<String, Object>();
        try {
            info.setCreator(UserUtils.getUser().getId());
            info.setUnit_id(unitId);
            Date date = new Date();
            info.setCreate_time(date);
            info.setShow_channel(GlobalValue.NO);
            channelService.saveChannelAll(info);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return toJsonSuccessData();
    }*/

    /**
     * 根据频道属性预览
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "previewH5", produces = "application/json; charset=utf-8")
    @ResponseBody
    public String previewH5(HttpServletRequest request, Integer unitId, Channel info, String columns) {
        try {
            info.setUnit_id(UserUtils.getUser().getRootUnit().getId());
            return toJsonSuccessData(channelService.previewH5(info, columns));

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 查询新闻频道
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "getNewsChannelList", produces = "application/json; charset=utf-8")
    @ResponseBody
    public String getNewsChannelList(HttpServletRequest request) {
        try {
            return toJsonSuccessData(channelService.getNewsChannelList(UserUtils.getUser().getRootUnit().getId()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 查询所有新闻频道
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "getAllChannelList", produces = "application/json; charset=utf-8")
    @ResponseBody
    public String getAllChannelList(HttpServletRequest request) {
        try {
            return toJsonSuccessData(channelService.getAllChannelList(UserUtils.getUser().getRootUnit().getId()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 预览
     *
     * @param request
     * @param channel_type
     * @param channel_short
     * @return
     */
    @RequestMapping(value = "qrView")
    @ResponseBody
    public String qrView(HttpServletRequest request, Integer channel_type, Integer channel_short) {
        String pv = "info";
        if (channel_type == 2) {
            pv = "comm";
        } else if (channel_type == 3) {
            pv = "live";
        }
        int unitId = UserUtils.getUser().getRootUnit().getId();

        Map<String, Object> map = channelService.getChannelByShort(unitId, channel_short);
        Date date = new Date();
        Channel channel = new Channel();
        channel.setCreate_time(date);
        channel.setChannel_type(Channel.CHANNEL_TYPE_0);
        channel.setChannel_short(channel_short);
        channel.setUnit_id(unitId);
        if (map == null) {
            channelDao.save(channel);

        }else{
            channel.setId(Integer.parseInt(map.get("id").toString()));
        }
        String baseUrl = "";
        if (request.getServerPort() == 80 || request.getServerPort() == 443 ) {
            baseUrl = request.getScheme() + "://" + request.getServerName() + request.getContextPath();
        } else {
            baseUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
        }
        String url = baseUrl + "/app/page?pv=" + pv + "&channelShort=" + channel.getId() + "&unit_id=" + getLoginUser().getUnit_id();
        String img = QRUtils.qrCodeBase64(url, 300, 300);
        map.put("url", url);
        map.put("img", img);
        return toJsonSuccessData(map);
    }

    @RequestMapping(value = "qrCode")
    @ResponseBody
    public String qrView(String url) {
        Map<String, Object> map = new HashMap<>();
        map.put("url", url);
        String img = QRUtils.qrCodeBase64(url, 300, 300);
        map.put("img", img);
        return toJsonSuccessData(map);
    }

    /**
     * 下载
     *
     * @param response
     * @param url
     */
    @RequestMapping(value = "downView")
    public void downView(HttpServletResponse response, String url, Integer type) {
        try {
            if(type == null){
                type = 1;
            }
            String fileName = new String((System.currentTimeMillis() + ".jpg").getBytes("utf8"), "iso-8859-1");
            QRUtils.downQrCode(response, fileName, url, type);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
